<template>
  <div class="container">
    <div v-if="skeletonLoading" class="skeleton-box">
      <div class="skeleton-animate"></div>
      <div
        class="skeleton-layer layer-1 animate-blink bg-box"
        :style="{
          marginTop: headNavHeight ? (headNavHeight + 16) + 'px' : '80px',
        }"></div>
      <div class="skeleton-layer layer-2 flex mar-t-16">
        <span v-for="(item, index) in 5" :key="index" class="flex-item mar-r-10 animate-blink bg-box"></span>
      </div>
      <div v-for="(itemG, indexG) in 2" :key="indexG">
        <div class="skeleton-layer layer-3 animate-blink bg-box height-33 mar-t-16"></div>
        <div v-for="(item, index) in 2" :key="index" class="skeleton-layer layer-4 flex mar-t-16">
          <div class="width-116 height-116 mar-r-12 animate-blink bg-box"></div>
          <div class="flex-item">
            <span class="animate-blink bg-box height-30"></span>
            <span class="bar-s animate-blink bg-box width-70 height-30 mar-t-12"></span>
          </div>
        </div>
      </div>
    </div>
    <header-nav :dataInfo="resData"></header-nav>
    <template v-if="!getCustomerId">
      <get-user-info v-if="isGetUserInfo" pageType="home" @updateUserInfo="initMemberInfo" @showTabBar="showTabBar"></get-user-info>
    </template>
    <custom-page :content="detailsList" @categoryLink="categoryLink"></custom-page>
    <div class="fixed-box" style="min-height: 600px;" v-if="!categoryNoData">
      <fixed-component 
        :categoryList="categoryList" 
        :goodsList="goodsList" 
        :top="headNavHeight"
        @onChange="categoryChange" 
        @categoryAction="categoryAction"
        :categoryActiveId="categoryId"></fixed-component>
      <div class="nodata" v-if="nodata">
        <div class="align-c" style="padding-top: 80px">
          <img v-if="fileSpace" :src="fileSpace + '/images/anchor-nodata.png'" class="width-205 height-173" alt="">
          <div class="align-c mar-t-5 font-16 font-color-9">
            暂无数据
          </div>
        </div>
      </div>
    </div>
    <!-- 注册栏 -->
    <register-bar v-if="registerBoolean"></register-bar>
    <!-- 选择身份：主播、中介 -->
    <user-type v-if="userTypeBoolean" ref="loginLayer"></user-type>
  </div>
</template>

<script>
import headerNav from '@/components/headerNav'
import GetUserInfo from '@/components/GetUserInfo'
import RegisterBar from '@/components/RegisterBar'
import UserType from '@/components/UserType'
import CustomPage from '@/components/CustomPage/index'
import FixedComponent from './components/FixedComponent/index'
import { getHomePage, getMemberInfo, listAllCategory, pagingMyProjectGoods } from '@/api/home'
import { checkLogin, getAuth } from '@/api/login'
import {
  setAnchorType,
  setNickName,
  setAppInfo,
  setCustomerId,
  setIsPerfectionInfo,
  setEnterpriseId,
  setOpenId,
  setRoleType,
  setPhone,
  setShowBuyCard,
  setMemberId
} from '@/utils/auth'
import { getAppInfo, getByEnterpriseId, checkIsLogin } from '@/api/common'
export default {
  components: { GetUserInfo, headerNav, RegisterBar, CustomPage, FixedComponent, UserType },
  data() {
    return {
      memberInfo: {},
      resData: {},
      detailsList: [],
      detailsNone: false,
      isGetUserInfo: false,
      showPhonePage: '0',
      registerBoolean: false,
      getEnterpriseId: '',
      getDefaultMemberId: '',
      categoryList: [],
      goodsList: [],
      currentPage: 1,
      categoryParams: {},
      nodata: false,
      categoryNoData: false,
      categoryId: '',
      pullLoad: {
        finished: false,
        loading: false
      },
      appInfo: {},
      headNavHeight: 0,
      skeletonLoading: true,
      userTypeBoolean: false,
      finishedEls: false,
      authCustomerId: '',
      authPhone: '',
      authCustomerData: false
    }
  },
  onLoad(options) {
    // 初始化data
    if ('showPhonePage' in options) {
      this.showPhonePage = '1'
      let that = this
      setTimeout(function() {
        if (that.getCustomerId && !that.getPhone) {
          that.isGetPhoneInfo = true
          that.$pt.hideTabBar({animation: false})
        }
      }, 1500)
    }
    Object.assign(this.$data, this.$options.data())
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    let sysInfo = ''
    sysInfo = this.$pt.getSystemInfoSync()
    if (sysInfo.system.indexOf('iOS') === -1) {
      // android类型
      this.$pt.setStorageSync('iOS', false)
    } else {
      this.$pt.setStorageSync('iOS', true)
    }
    this.$pt.setStorageSync('devW', wx.getSystemInfoSync().windowWidth)
  },
  async onShow() {
    this.$pt.showTabBar({
      animation: false
    })
    if (this.$pt.getStorageSync('openId')) {
      await this.checkIsLogin(this.$pt.getStorageSync('openId'))
      if (this.authCustomerData && this.getRoleType !== 2) {
        await this.authAgainEls()
      }
    }
    this.finishedEls = false
    this.initAppInfo()
    this.initHomeEls()
    this.getByEnterpriseId()
    if (this.$pt.getStorageSync('anchorBack')) {
      this.$pt.removeStorageSync('anchorBack')
      this.$pt.showLoading({title: '加载中...'})
      setTimeout(() => {
        this.$pt.hideLoading()
      }, 800)
      this.initPageGoodsEls()
    }
    if (this.$pt.getStorageSync('anchorAuth')) {
      this.$pt.removeStorageSync('anchorAuth')
    }
    if (this.userTypeBoolean) {
      this.hideTabBar()
    }
  },
  async mounted() {
    if (!this.$pt.getStorageSync('openId') || !this.$pt.getStorageSync('showBuyCard')) {
      await this.authEls()
    }
    await this.checkIsLogin(this.$pt.getStorageSync('openId'))
    if (this.authCustomerData && this.getRoleType !== 2) {
      await this.authAgainEls()
    }
    this.initPageGoodsEls()
  },
  onShareAppMessage() {
    // 分享名片埋点
    return {
      title: this.resData.shareTitle ? this.resData.shareTitle : '选品就是方便',
      path: 'pages/home/main',
      imageUrl: this.resData.sharePicUrl ? this.resData.sharePicUrl : this.fileSpace + '/images/share-s-anchor-picture.png'
    }
  },
  onShareTimeline() {
    return {
      title: this.resData.shareTitle ? this.resData.shareTitle : '选品就是方便',
      imageUrl: this.resData.sharePicUrl ? this.resData.sharePicUrl : this.fileSpace + '/images/share-s-anchor-picture.png',
      query: ''
    }
  },
  // 下拉刷新
  async onPullDownRefresh() {
    Object.assign(this.$data, this.$options.data())
    this.skeletonLoading = true
    await this.checkIsLogin(this.$pt.getStorageSync('openId'))
    this.initHomeEls()
    this.finishedEls = false
    this.goodsList = []
    this.currentPage = 1
    this.nodata = false
    this.pullLoad.finished = false
    this.initPageGoodsEls()
    setTimeout(() => {
      this.$pt.stopPullDownRefresh()
    }, 80)
  },
  onReachBottom() {
    // 触底刷新
    if (!this.pullLoad.finished && !this.categoryNoData && this.getShowBuyCard) {
      setTimeout(() => {
        this.pagingMyProjectGoods(this.categoryParams)
      }, 300)
    }
  },
  methods: {
    async changeReload() {
      await this.checkIsLogin(this.$pt.getStorageSync('openId'))
    },
    loginBackEls() {
      this.initPageGoodsEls()
    },
    initPageGoodsEls() {
      this.getHomePage()
      this.listAllCategory()
      this.$nextTick(() => {
        let query = this.$pt.createSelectorQuery().selectAll('.top-name-bar')
        query.boundingClientRect(rects => {
          let rect = rects[0]
          this.headNavHeight = rect.height
        }).exec()
      })
    },
    initAppInfo() {
      getAppInfo().then((response) => {
        if (response.isError) return
        this.appInfo = response.data
        if (response.data.enterpriseId) {
          setEnterpriseId(response.data.enterpriseId)
        }
        setAppInfo(this.appInfo)
        // 小程序朋友圈分享
        if (wx.getLaunchOptionsSync().scene && wx.getLaunchOptionsSync().scene === 1154) {
          setMemberId(response.data.defaultMemberId)
          this.$pt.setStorageSync('memberId', response.data.defaultMemberId)
          this.$pt.setStorageSync('myId', response.data.defaultMemberId)
          this.$pt.setStorageSync('enterpriseId', response.data.enterpriseId)
          setEnterpriseId(response.data.enterpriseId)
          this.$pt.setStorageSync('showBuyCard', true)
          this.getHomePage()
        }
      }).catch(() => {
      })
    },
    getByEnterpriseId() {
      // 获取企业参数配置
      getByEnterpriseId().then(response => {
        if (response.isError) return
        // response.data.isOpenAnchorCompulsoryPerfectionInfo = 0
        if (response.data.isOpenAnchorCompulsoryPerfectionInfo) {
          setIsPerfectionInfo(response.data.isOpenAnchorCompulsoryPerfectionInfo)
        } else {
          setIsPerfectionInfo(0)
        }
      }).catch({})
    },
    showTabBar() {
      this.$pt.showTabBar({
        animation: false
      })
    },
    hideTabBar() {
      this.$pt.hideTabBar({
        animation: false
      })
    },
    getAppInfoEls() {
      getAppInfo().then((response) => {
        if (response.isError) return
        this.appInfo = response.data
        setAppInfo(this.appInfo)
        if (this.appInfo.enterpriseId) {
          this.getEnterpriseId = this.appInfo.enterpriseId
          this.getDefaultMemberId = this.appInfo.defaultMemberId
          this.getHomePage()
          this.listAllCategory()
        }
      }).catch(() => {
      })
    },
    initHomeEls() {
      if (this.getCustomerId) {
        this.initCustomerInfo()
      } else {
        checkLogin()
        this.$pt.setStorageSync('homeNone', true)
      }
    },
    authEls() {
      return new Promise((resolve, reject) => {
        let that = this
        this.$pt.login({
          success(res) {
            if (res.code) {
              getAuth(res.code).then((response) => {
                if (response.data.openId) {
                  setOpenId(response.data.openId)
                }
                if (response.data.customerId) {
                  that.authCustomerId = response.data.customerId
                }
                if (response.data.phone) {
                  that.authPhone = response.data.phone
                }
                if (response.data.showBuyCard) {
                  setShowBuyCard(response.data.showBuyCard)
                }
                resolve(true)
              }).catch(() => {
              })
            }
          }
        })
      })
    },
    authAgainEls() {
      return new Promise((resolve, reject) => {
        this.$pt.login({
          success(res) {
            if (res.code) {
              getAuth(res.code).then((response) => {
                if (response.data.customerId) {
                  setCustomerId(response.data.customerId)
                }
                if (response.data.showBuyCard) {
                  setShowBuyCard(response.data.showBuyCard)
                }
                resolve(true)
              }).catch(() => {
              })
            }
          }
        })
      })
    },
    nextTickLoginEls() {
      this.$nextTick(() => {
        this.$refs.loginLayer.selUser(2)
      })
    },
    checkIsLogin(openId) {
      return new Promise((resolve, reject) => {
        checkIsLogin({ openId: openId }).then((response) => {
          if (response.isError) return
          // response.code = 5001
          if (response.code === 5000 && this.getCustomerId) {
            // 没登录过
            this.$pt.setStorageSync('loginCode', response.code)
          }
          if (response.code === 5001) {
            // 中介登录账号密码，存在异常
            setCustomerId('')
            setPhone('')
            setNickName('')
            setRoleType('')
            this.registerBoolean = false
            this.$utils.showToast({ title: response.msg })
            this.userTypeBoolean = true
            this.hideTabBar()
            this.nextTickLoginEls()
            this.$pt.setStorageSync('loginCode', response.code)
          }
          if (response.code === 101) {
            // this.registerBoolean = false
            setRoleType(response.data.roleType)
            switch (response.data.roleType) {
              case 1:
                // 主播身份
                this.$pt.setStorageSync('loginCode', 1)
                if (!response.data.customerMemberId && this.authCustomerId) {
                  setCustomerId(this.authCustomerId)
                }
                this.authCustomerData = false
                if (!response.data.customerMemberId && !this.authCustomerId) {
                  this.authCustomerData = true
                }
                if (!response.data.customerMemberId && this.authPhone) {
                  setPhone(this.authPhone)
                }
                if (response.data.customerMemberId) {
                  setCustomerId(response.data.customerMemberId)
                }
                break
              case 2:
                // 中介身份
                this.registerBoolean = false
                setCustomerId(response.data.partnerId)
                setPhone(response.data.phone)
                if (response.data.partnerName) {
                  setNickName(response.data.partnerName)
                }
                if (response.data.enterpriseId) {
                  setEnterpriseId(response.data.enterpriseId)
                }
                setAnchorType(1)
                this.$pt.setStorageSync('loginCode', 2)
                break
            }
          }
          this.initCustomerInfo()
          resolve(true)
        }).catch(() => {
        })
      })
    },
    userPhoneLayer(scanIn) {
      if (!this.getCustomerId && scanIn) {
        this.$pt.hideTabBar({
          animation: false
        })
        this.isGetUserInfo = false
        setTimeout(() => {
          this.isGetUserInfo = true
        }, 100)
      }
      if (!this.$pt.getStorageSync('phone') && (scanIn || this.showPhonePage === '1')) {
        this.$pt.hideTabBar({
          animation: false
        })
        this.isGetPhoneInfo = false
        setTimeout(() => {
          this.isGetPhoneInfo = true
        }, 100)
      }
      if (this.$pt.getStorageSync('phone') && scanIn) {
        this.$pt.showTabBar({
          animation: false
        })
        this.isGetPhoneInfo = false
      }
      if (!this.getCustomerId && scanIn) {
        this.$pt.hideTabBar({
          animation: false
        })
        this.isGetUserInfo = false
        setTimeout(() => {
          this.isGetUserInfo = true
        }, 100)
      }
    },
    initMemberInfo() {
      this.initCustomerInfo()
      this.getHomePage()
      this.listAllCategory()
      // 如果缓存没有手机号码，则弹出微信授权手机号码
      const scanIn = this.$pt.getStorageSync('scanIn')
      const scanCode = this.$pt.getStorageSync('scanCode')
      if (this.getCustomerId && this.getPhone && scanIn && scanCode) {
        this.$pt.showTabBar({
          animation: false
        })
        setTimeout(() => {
          this.$pt.reLaunch({
            url: '/pages/home/get-card/main?salesData=' + scanCode
          })
        }, 300)
        return
      }
      this.userPhoneLayer(scanIn)
    },
    // 会员基本信息
    initCustomerInfo() {
      if (this.getRoleType === 2) return
      getMemberInfo(this.getCustomerId).then((response) => {
        if (response.isError) return
        this.customerInfo = response.data
        setNickName(this.customerInfo.nickname)
        if (this.customerInfo.anchorAuthority !== undefined) {
          setAnchorType(this.customerInfo.anchorAuthority)
        }
        if (this.customerInfo.anchorAuthority) {
          this.registerBoolean = false
          setRoleType(1)
        } else {
          this.registerBoolean = true
        }
      }).catch(() => {
      })
    },
    getHomePage() {
      // 初次获取不到企业ID和默认memberId时，先调用getAppInfoEls获取
      if (!this.getEnterpriseId || !this.getDefaultMemberId) {
        this.getAppInfoEls()
        return
      }
      let params = {
        enterpriseId: this.getEnterpriseId,
        memberId: this.getDefaultMemberId,
        customerId: this.getCustomerId,
        // roleType: ''
        roleType: this.getRoleType ? this.getRoleType : ''
      }
      this.skeletonLoading = true
      getHomePage(params).then(response => {
        if (response.isError) return
        this.$pt.hideToast()
        this.skeletonLoading = false
        if (Object.keys(response.data).length !== 0) {
          this.resData = response.data
          if (this.resData.titleType === 10) {
            this.$pt.setNavigationBarColor({
              frontColor: '#ffffff',
              backgroundColor: this.resData.titleBackgroundColor
            })
          } else {
            this.$pt.setNavigationBarColor({
              frontColor: '#000000',
              backgroundColor: this.resData.titleBackgroundColor
            })
          }
          let dataList = response.data.detailsList ? response.data.detailsList : []
          if (!dataList.length) {
            this.detailsNone = true
          } else {
            this.detailsNone = false
            this.detailsList = dataList
            this.detailsList.forEach(item => {
              if (item.componentType === 12 && item.pictureList && item.pictureList.length && !this.$pt.getStorageSync('iOS')) {
                let that = this
                wx.getImageInfo({
                  src: item.pictureList[0].imgUrl,
                  success(e) {
                    if (item.propMap.picStyle === '10' && !that.$pt.getStorageSync('iOS')) {
                      item.pictureList[0].height = ((that.$pt.getStorageSync('devW') * e.height) / e.width) - item.propMap.verticalMargin * 1
                      item.propMap.pictureHeight = item.pictureList[0].height
                    }
                    if (item.propMap.picStyle !== '10' && !that.$pt.getStorageSync('iOS')) {
                      item.pictureList[0].height = ((that.$pt.getStorageSync('devW') / 2 * e.height) / e.width) - item.propMap.verticalMargin * 1
                      item.propMap.pictureHeight = item.pictureList[0].height
                    }
                  }
                })
              }
              if (item.componentType === 19 && item.swiperList && item.swiperList.length) {
                let that = this
                wx.getImageInfo({
                  src: item.swiperList[0].imgUrl,
                  success(e) {
                    if (item.propMap.swiperStyle === '10') {
                      item.swiperList[0].height = ((that.$pt.getStorageSync('devW') * e.height) / e.width) - item.propMap.verticalMargin * 1
                      item.propMap.swiperHeight = item.swiperList[0].height
                    }
                    if (item.propMap.swiperStyle !== '10') {
                      item.swiperList[0].height = ((that.$pt.getStorageSync('devW') / 2 * e.height) / e.width) - item.propMap.verticalMargin * 1
                      item.propMap.swiperHeight = item.swiperList[0].height
                    }
                  }
                })
              }
            })
          }
        } else {
          this.resData = {}
          this.detailsList = []
          this.detailsNone = true
          this.$pt.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff'
          })
        }
      })
    },
    // 获取商品分类
    listAllCategory() {
      // 初次获取不到企业ID和默认memberId时，先调用getAppInfoEls获取
      if (!this.getEnterpriseId) {
        return
      }
      this.categoryNoData = false
      listAllCategory(this.getEnterpriseId).then(response => {
        if (response.isError) return
        if (response.data.length === 0) {
          this.categoryNoData = true
        }
        this.categoryList = response.data
        this.categoryList.unshift({
          categoryId: '',
          categoryName: '全部',
          enterpriseCategoryId: ''
        })
        this.categoryParams.categoryActive = this.categoryList[0].enterpriseCategoryId
        this.categoryParams.createTimeSort = 1
        this.categoryParams.roleType = this.getRoleType
        this.goodsList = []
        this.currentPage = 1
        this.nodata = false
        this.pullLoad.finished = false
        this.pagingMyProjectGoods(this.categoryParams)
      }).catch(() => {
      })
    },
    // 获取分类商品
    pagingMyProjectGoods(categoryParams) {
      let params = {
        categoryId: categoryParams.categoryActive,
        size: 6,
        currentPage: this.currentPage,
        roleType: this.getRoleType || '',
        memberId: this.getDefaultMemberId,
        customerId: this.getCustomerId,
        enterpriseId: this.getEnterpriseId,
        createTimeSort: categoryParams.createTimeSort || '', // 新品排序
        salesNumSort: categoryParams.salesNumSort || '', // 销售排序
        anchorRatioSort: categoryParams.anchorRatioSort || '' // 佣金排序
      }
      this.finishedEls = true
      return pagingMyProjectGoods(params).then(response => {
        if (response.isError) return
        if (response.data.total === 0) {
          this.nodata = true
          this.pullLoad.finished = true
          return
        }
        response.data.records.forEach(item => {
          // 网红在卖人数
          item.anchorSalePeople = item.putawayNum + item.virtualPutawayNum
          this.goodsList.push(item)
        })
        setTimeout(() => {
          this.finishedEls = false
        }, 800)
        this.currentPage++
        if (this.goodsList.length === 0 || this.goodsList.length >= response.data.total) {
          this.pullLoad.finished = true
        }
        // return true
      }).catch(() => {
      })
    },
    // 监听固定组件区域筛选发生变化
    categoryChange(params) {
      this.categoryParams = params
      this.goodsList = []
      this.currentPage = 1
      this.nodata = false
      this.pullLoad.finished = false
      this.pagingMyProjectGoods(this.categoryParams)
    },
    categoryAction(categoryId) {
      this.categoryId = categoryId
    },
    // 自定义组件分类链接
    async categoryLink(item) {
      this.categoryId = item.categoryId
      this.categoryParams.categoryActive = item.categoryId
      this.goodsList = []
      this.currentPage = 1
      this.nodata = false
      this.pullLoad.finished = false
      await this.pagingMyProjectGoods(this.categoryParams)
      // 监听固定组件在屏幕的位置
      this.$pt.pageScrollTo({ selector: '.fixed-box' })
    }
  }
}
</script>

<style scoped lang="less">
  .container{
    background: #fff;
    min-height: 100vh;
    .skeleton-box{
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: 1100;
      background-color: #fff;
      overflow: hidden;
      .skeleton-layer{
        margin: 15px;
        &.bg-box{
          border-radius: 10px;
          background-color: #f5f5f5;
        }
        .bg-box{
          border-radius: 10px;
          background-color: #f5f5f5;
        }
        &.layer-1{
          margin-top: 80px;
          height: 110px;
        }
        &.layer-2{        
          span{
            display: block;
            height: 60px;
            &:last-child{
              margin-right: 0!important;
            }
          }
        }
        &.layer-4{
          .flex-item{
            span{
              display: block;
              border-radius: 5px;
            }
          }
        }
      }
    }
    .skeleton-layer-bg{
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: #fff;
      z-index: 99;
    }
  }
</style>
